import json
from uuid import uuid4
from django.shortcuts import render, reverse, redirect
from django.http import JsonResponse

from web.forms.issues import AddWorkOrderModelForm
from utils.paginate import Pagination
from web import models


def common(request):
    """ 分页通用函数 """
    try:
        if int(request.GET.get("page", 1)) > 0:
            page_number = int(request.GET.get("page", 1))
        else:
            page_number = 1
    except Exception:
        page_number = 1
    # 表内的数据条数
    item_count = models.WorkOrder.objects.all().count()
    # 每页显示的数据条目数
    per_page_number = 5
    # 总页数需要多少页，不足一页得也需要一页显示
    total_page, b = divmod(item_count, per_page_number)
    if b:
        total_page += 1
    # 窗口中显示得页码个数
    show_page_nums = 7
    # 实例化分页类
    page_info_obj = Pagination(
        current_page=page_number,  # 当前请求页
        all_count=item_count,
        base_url=request.path_info,
        query_params=request.GET,
        per_page=per_page_number,
        pager_page_count=show_page_nums
    )
    return page_info_obj


def common_data_request():
    pass


def issues(request, project_id):
    if request.method == 'GET':
        is_issue_home_page = request.path_info.endswith('issues/')
        page_info_obj = common(request)
        item_list = models.WorkOrder.objects.filter(project_id=project_id).exclude(
            order_status=6).all()[page_info_obj.start: page_info_obj.end]  # 获取分页后的列表

        form = AddWorkOrderModelForm(request)
        context = {
            'form': form,
            'item_list': item_list,
            'page_list_html': page_info_obj.page_html(),
            'is_issue_home_page': is_issue_home_page
        }
        return render(request, 'web/workorder/issues.html', context)
    form = AddWorkOrderModelForm(request, data=request.POST)
    if form.is_valid():
        form.instance.order_id = str(uuid4())
        form.instance.status_link = json.dumps(
            [{'user': request.login_user.user.username,
              'status': form.instance.order_status.order_status}])
        form.instance.update_user = request.login_user.user
        form.instance.project = request.login_user.project
        form.save()
        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def issues_detail(request, project_id, order_id):
    order_object = models.WorkOrder.objects.filter(id=order_id, project_id=project_id).first()
    if request.method == 'GET':
        # 获取工单状态表信息
        status_list = [(0, '请修改工单状态'), ]
        obj_ = models.WorkOrderStatus.objects.all().values_list('id', 'order_status')
        status_list.extend(obj_)
        # 获取用户表信息
        user_list = [(0, '请选择将此工单指派给谁'), ]
        user_list.extend(models.UserInfo.objects.all().values_list('id', 'username'))

        if not order_object:
            return redirect('issues', kwargs={'project_id': project_id})
        status_link_list = json.loads(order_object.status_link)  # [{'zhaojianfei': '处理中'}]
        # 如果当前的工单的指派者是当前的登录用户，页面出现执行工单的按钮
        if request.login_user.user == order_object.assign_user:
            allowed = True
        else:
            allowed = False

        # 获取属于这个工单的所有评论信息
        comment_list = models.WorkOrderComment.objects.filter(order_id=order_id, parent_comment__isnull=True).all()
        context = {
            'allowed': allowed,
            'status_link_list': status_link_list,
            'order_object': order_object,
            'status_list': status_list,
            'user_list': user_list,
            'comment_list': comment_list
        }
        return render(request, 'web/workorder/issues_detail.html', context)
    status_id = request.POST.get('status')
    assign_id = request.POST.get('assign')
    comment = request.POST.get('comment')
    if int(status_id) < 1:
        return JsonResponse({'status': False, 'errors': {'status': ['状态选择错误', ]}})
    if int(assign_id) < 1:
        # 如果谁也不指派，那么指派人默认是操作者
        assign_id = request.login_user.user.id
    status_obj = models.WorkOrderStatus.objects.filter(id=status_id).first()

    # 操作工单表
    order_object.order_status_id = status_id
    order_object.assign_user_id = assign_id
    order_object.update_user_id = request.login_user.user.id
    old_status_link = json.loads(order_object.status_link)

    old_status_link.append({'user': request.login_user.user.username, 'status': status_obj.order_status})
    order_object.status_link = json.dumps(old_status_link)

    order_object.save()
    # 操作评论表
    models.WorkOrderComment.objects.create(
        content=comment,
        order_id=order_id,
        user=request.login_user.user
    )
    return JsonResponse({'status': True})


def issues_myself(request, project_id):
    if request.method == 'GET':
        page_info_obj = common(request)
        is_issue_home_page = request.path_info.endswith('issues/')
        my_order_list = models.WorkOrder.objects.filter(project_id=project_id,
                                                        assign_user=request.login_user.user).all()[
                        page_info_obj.start: page_info_obj.end]
        context = {
            'my_order_list': my_order_list,
            'is_issue_home_page': is_issue_home_page,
            'my_order_page_html': page_info_obj.page_html()
        }
        return render(request, 'web/workorder/myorder.html', context)


def issues_all(request, project_id):
    if request.method == 'GET':
        page_info_obj = common(request)
        is_issue_home_page = request.path_info.endswith('issues/')

        all_order_list = models.WorkOrder.objects.filter(project_id=project_id).all()[
                         page_info_obj.start: page_info_obj.end]  # 获取分页后的列表
        context = {
            'all_order_list': all_order_list,
            'all_order_page_html': page_info_obj.page_html(),
            'is_issue_home_page': is_issue_home_page
        }
        return render(request, 'web/workorder/allorder.html', context)


def issues_select(request, project_id):
    pass
